package org.csu.mybigpro.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.csu.mybigpro.DTO.ResourceAnalysisDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

@Service
public class ResourceService {

    @Autowired
    private WordParserService wordParserService; // 复用已有的Word解析器

    @Autowired
    private AiService aiService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    public ResourceAnalysisDto analyzeDocument(MultipartFile file) throws Exception {
        // 1. 解析文档内容 (当前仅支持Word，未来可扩展为通用解析器)
        String text = wordParserService.extractText(file);
        if (text == null || text.isBlank()) {
            throw new Exception("无法从文档中提取任何文本内容。");
        }

        // 2. 并行调用AI进行分析 (这里为了逻辑清晰，采用串行，未来可优化为并行)
        ResourceAnalysisDto analysisResult = new ResourceAnalysisDto();

        // 2.1 提取标签
        String tagsJson = aiService.generateTags(text);
        analysisResult.setTags(parseJsonArray(tagsJson));

        // 2.2 生成摘要
        String summaryJson = aiService.generateSummary(text);
        JsonNode summaryNode = objectMapper.readTree(extractJsonContent(summaryJson));
        analysisResult.setSummary(summaryNode.path("summary").asText(""));

        // 2.3 提取知识点
        String pointsJson = aiService.extractKnowledgePoints(text);
        analysisResult.setKnowledgePoints(parseJsonArray(pointsJson));

        // 2.4 生成练习题
        String questionsJson = aiService.generatePracticeQuestions(text);
        List<Map<String, Object>> questions = objectMapper.readValue(extractJsonContent(questionsJson), new TypeReference<>() {});
        analysisResult.setGeneratedQuestions(questions);

        return analysisResult;
    }

    /**
     * 辅助方法：从AI的完整响应中提取出核心的JSON字符串。
     * @param rawResponse AI返回的原始JSON字符串
     * @return 清理后的JSON内容
     * @throws Exception 解析失败时抛出异常
     */
    private String extractJsonContent(String rawResponse) throws Exception {
        JsonNode rootNode = objectMapper.readTree(rawResponse);
        String textContent = rootNode.path("candidates").path(0).path("content").path("parts").path(0).path("text").asText();

        // 处理可能存在的Markdown代码块
        if (textContent.startsWith("```json")) {
            return textContent.substring(7, textContent.lastIndexOf("```")).trim();
        }
        return textContent;
    }

    /**
     * 辅助方法：将AI返回的JSON数组字符串解析为List<String>
     */
    private List<String> parseJsonArray(String jsonResponse) throws Exception {
        String content = extractJsonContent(jsonResponse);
        return objectMapper.readValue(content, new TypeReference<List<String>>() {});
    }
}